package com.bdzl.pub.util.file;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 根据模板导出pdf
 */
public class PdfUtil {
    Logger LOG = LoggerFactory.getLogger(getClass());
    /**
     *
     * @param o 写入的数据
     * @param out 自定义保存pdf的文件流
     * @param templatePath pdf模板路径
     */
    // 利用模板生成pdf
    public  void fillTemplate(Map<String,Object> o,ServletOutputStream out,String templatePath) {
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
//此处的字体,服务要是在linux上,中文会出现导出填不上的情况,所以,此处字体必填
            BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Font FontChinese = new Font(bf, 5, Font.NORMAL);
            reader = new PdfReader(templatePath);// 读取pdf模板
            //FileInputStream is = new FileInputStream(fileTemplate);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            form.addSubstitutionFont(bf);
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                String value = o.get(name)!=null?o.get(name).toString():null;
                LOG.info("名字:{},标签:{}",value,name);
                form.setField(name,value);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            LOG.info("插入成功");
            Document doc = new Document();
            Font font = new Font(bf, 32);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            //循环是处理成品只显示一页的问题
            PdfImportedPage importPage = null;
            for (int  i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            doc.close();

        } catch (IOException e) {
            LOG.error("利用模板导出PDF失败:{}",e);
        } catch (DocumentException e) {
            LOG.error("利用模板导出PDF失败:{}",e);
        }
    }
}
